#!/sbin/openrc-run

name=tootik
description="Tootik is a federated nanoblogging service for the small internet"

extra_commands="addcomm confuser"
description_addcomm="Add a community"
description_confuser="Configure user/community"

: ${httpscert:="/etc/tootik/https-cert.pem"}
: ${httpskey:="/etc/tootik/https-key.pem"}
: ${gemcert:="/etc/tootik/gemini-cert.pem"}
: ${gemkey:="/etc/tootik/gemini-key.pem"}
: ${tootik_cfg:="/etc/tootik/tootik.cfg"}
: ${tootik_db:="/var/lib/tootik/db.sqlite3"}

command="/usr/bin/tootik"
command_args="
	${blocklist:+-blocklist $blocklist}
	${httpaddr:+-addr $httpaddr}
	${tootik_domain:+-domain $tootik_domain}
	-cfg $tootik_cfg
	-db $tootik_db
	${gemaddr:+-gemaddr $gemaddr}
	-gemcert $gemcert
	-gemkey $gemkey
	${fingeraddr:+-fingeraddr $fingeraddr}
	${gopheraddr:+-gopheraddr $gopheraddr}
	${guppyaddr:+-guppyaddr $guppyaddr}
	${loglevel:+-loglevel $loglevel}
	$extra_opts
	"
command_background="yes"
command_user="tootik:tootik"
pidfile="/run/${RC_SVCNAME}.pid"
directory="/var/lib/tootik"
error_log="/var/log/tootik.log"
required_files="$tootik_cfg"

if yesno "${disable_registration:-no}"; then
	command_args="$command_args -closed"
fi

if yesno "${serve_https:-no}"; then
	command_args="$command_args -cert $httpscert -key $httpskey"
	required_files="$required_files $httpscert $httpskey"
else
	command_args="$command_args -plain"
fi

depend() {
	need localmount net
	after firewall
}

start_pre() {
	checkpath -d -m 0750 -o "$command_user" \
		"$directory" "/etc/tootik"

	if [ ! -f "$gemcert" ] || [ ! -f "$gemkey" ]; then
		gen_gemcert || return 1
	fi

	checkpath -f -m 0640 -o "$command_user" \
		"$error_log" "$gemcert" "$gemkey" "$tootik_cfg"
}

gen_gemcert() {
	local domain="${tootik_domain:-localhost.localdomain:8443}"

	ebegin "Generating new Gemini TLS key & certificate for $domain"
	openssl req -new -subj "/CN=$domain" -x509 -days 3650 \
		-newkey ec -pkeyopt ec_paramgen_curve:prime256v1 \
		-sha256 -nodes -out "$gemcert" -keyout "$gemkey" \
		2>/dev/null
	eend $?
}

addcomm() {
	read -p "community: " community

	ebegin "Creating community on ${tootik_domain:-Tootik}: '$community'"
	tootik_exec add-community "$community"
	eend $?
}

confuser() {
	read -p "user/community: " username
	read -p "bio (file): " bio_file
	read -p "avatar (file): " avatar

	[ -f "$bio_file" ] && tootik_exec set-bio "$username" "$bio_file"
	[ -f "$avatar" ] && tootik_exec set-avatar "$username" "$avatar"
}

tootik_exec() {
	start-stop-daemon --exec "$command" --user "$command_user" \
		-- ${tootik_domain:+-domain $tootik_domain} \
		-db $tootik_db $*
}
